/**
 * Created by YiFeng on 2016/9/17.
 */
define(['ladder-core'], function (Ladder){
    Ladder.NS("Layout");
    Ladder.Layout = {
        init: function() {
            var layout = $("[data-layout]"), winW = "100%", WinH = $(window).height(), _this = this;
            var layouthead = layout.filter("[data-layout='head']");
            if (layouthead.length > 0)layouthead.css({ width: winW, height: 69 });
            var layoutfoot = layout.filter("[data-layout='foot']");
            if (layoutfoot.length > 0)layoutfoot.css({ width: winW, height: 30 });
            var layoutmain = layout.filter("[data-layout='main']");
            if (layoutmain.length > 0) {
                layoutmain.css({
                    width: winW,
                    position: "relative",
                    height: WinH - (layoutfoot.length > 0 ? layoutfoot.height() : 0) - (layouthead.length > 0 ? layouthead.outerHeight() : 0)
                });
            }
            var layoutleft = layout.filter("[data-layout='left']");
            var layoutright = layout.filter("[data-layout='right']");
            if (layoutleft.length)layoutleft.css({ "float": "left", "height": "100%" });
            if (layoutright.length) {
                layoutright.css({
                    height: "100%",
                    left: layoutleft.width(),
                    position: "absolute",
                    width: layoutmain.width() - (layoutleft.length > 0 ? layoutleft.width() : 0)
                });
            }
            //$(window).wresize(function(e) {
            //    layoutmain.css({
            //        height: $(window).height() - (layoutfoot.length > 0 ? layoutfoot.height() : 0) - (layouthead.length > 0 ? layouthead.height() : 0)
            //    });
            //    if (layoutright)layoutright.width($(window).width() - (layoutleft.length > 0 ? layoutleft.outerWidth() : 0));
            //
            //});
        },
        adjustMainW: function(l_left, l_width) {
            $("[data-layout='left']").animate({ left: l_left, width: l_width }, 500);
            var r_left = l_left + l_width > 0 ? l_left + l_width : 0;
            $("[data-layout='right']").animate({ left: r_left, width: $(window).width() - r_left }, 500);
        }
    };
    Ladder.NavTab=function(el,option){
        this.father=$(el);
        this.tabs=null;
        this.index=0;
        this.swapView=null;
        this.current=null;
        if(this.father.length<1)return;
        this.settings={
            height:40,
            view:null,
            viewHeight:"auto",
            viewWidth:"auto",
        };
        $.extend(this.settings,option);
        this.init()
    };
    Ladder.NavTab.prototype={
        init:function(){
            var me=this;
            //容器
            var $container = $("<div class='yui-navtabs'></div>").appendTo(this.father);
            //向左按钮
            var $scrollLeft=$('<button class="yui-navtabs-rollbtn leftRoll"><i class="iconfont">&#xe662;</i></button>').appendTo($container);
            //菜单区
            this.tabs=$('<nav class="yui-navtabs-content"><div class="yui-navtabs-menus"></div></nav>').appendTo($container).find(".yui-navtabs-menus");
//                this.tabs.append('<a href="javascript:;" class="yui-navtabs-tab">首页<i class="iconfont icon-close1"></i></a>');
            //向右按钮
            $('<button class="yui-navtabs-rollbtn rightRoll"><i class="iconfont">&#xe663;</i></button>').appendTo($container);
            //关闭选项
            var $closeSelect=$('<div class="btn-group"></div>').appendTo($container);
            $('<button class="closeSelect">操作选项<i class="iconfont">&#xe68a;</i></button>').appendTo($closeSelect).click(function(){
                $dropMenu.toggle("fast");
            });
            var $dropMenu=$('<ul class="dropdown-menu">' +
                '<li class="js-ShowActive"><a>定位当前选项卡</a></li>' +
                '<li class="js-CloseAll"><a>关闭全部选项卡</a></li>' +
                '<li class="js-CloseOther"><a>关闭其他选项卡</a></li>' +
                '</ul>').appendTo($closeSelect);
            $dropMenu.find(".js-CloseOther").click(function(){
                var $others = me.tabs.find(".current").siblings();
                $others.each(function(){
                    var $this=$(this);
                    if(!$this.attr("data-allowClose"))return;
                    me.swapView.find("#tabpage"+$this.attr("data-index")).remove();
                    $this.remove();
                });
                $dropMenu.toggle("fast");
            });
            $dropMenu.find(".js-CloseAll").click(function(){
                var $others = me.tabs.children();
                $others.each(function(){
                    var $this=$(this);
                    if(!$this.attr("data-allowClose"))return;
                    me.swapView.find("#tabpage"+$this.attr("data-index")).remove();
                    $this.remove();
                });
                $dropMenu.toggle("fast");
                me.tabs.find(".yui-navtabs-tab:last").trigger("click");
            });
            if(!this.settings.view){
                this.swapView=$("<div class='yui-navtabs-swapView' layoutH='4'></div>").appendTo(this.father);
                Ladder.layout(this.swapView);
            }else{
                this.swapView=$(this.settings.view);
            }
            if(this.settings.viewHeight=="auto"){
                this.settings.viewHeight = this.swapView.height();
            }
        },
        open:function(pagedata){
            var me=this;
            if(!pagedata || (!pagedata.url))return;
            //不允许重复打开
            if(pagedata.hasOwnProperty("repeat")&&pagedata.repeat==0&&me.tabs.find("[data-id='"+pagedata.id+"']").length>0){
                return;
            }
            Ladder.Service.setRequestInfo(pagedata);
            var title=pagedata.title;
            var url=pagedata.url;
            var icon=pagedata.icon;
            var index = me.index++;
            if(pagedata.type=='form'&&pagedata.openargs){
                var  args=$.param(Ladder.toJSON(pagedata.openargs));
                if(url.indexOf("?")>0){
                    url+="&"+args;
                }else{
                    url+="?"+args;
                }
            }
            url=Ladder.Service.parseUrl(url);
            if(pagedata.hasOwnProperty("openway") && pagedata.openway){
                if(pagedata.openway==1){
                    window.open(url);
                    return;
                }
                if(pagedata.openway==2){
                    var temp=Ladder.data(pagedata);
                    $width=(temp.get("width")||temp.get("param.width")||temp.get("openargs.width")||$width)+"";
                    $height=(temp.get("height")||temp.get("param.height")||temp.get("openargs.height")||$height)+"";
                    layer.open({
                        type: 2,
                        title: title,
                        shadeClose: true,
                        shade: 0.8,
                        area: [$width.replace(/px/i,"")+'px',$height.replace(/px/i,"")+'px'],
                        content:url  //iframe的url
                    });
                    return;
                }
            }
            var $nav=$('<a href="javascript:;" class="yui-navtabs-tab current">'+title+'</a>').appendTo(me.tabs);
            $nav.attr("data-index",index).attr("data-id",pagedata.id).data("pagedata",pagedata).click(function(){
                var $this = $(this);
                $this.addClass("current").siblings().removeClass("current");
                var $page=me.swapView.find("#tabpage"+$this.attr("data-index")).show();
                $page.siblings().hide();
            });
            if(pagedata.closeBtn!==false){
                $nav.append('<i class="iconfont icon-close"></i>');
                $nav.attr("data-allowClose",1);
                $nav.find(".icon-close").click(function(){
                    var $this = $(this).parent();
                    var $next=$this.next();
                    if($next.length<1)$next=$this.prev();
                    me.swapView.find("#tabpage"+$this.attr("data-index")).remove();
                    $this.remove();
                    $next.trigger("click");
                });
            }
            var $parent  = $('<div class="yui-navtabs-page"></div>').appendTo(me.swapView).height(me.settings.viewHeight);
            var $iframe=$('<iframe width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>').appendTo($parent);
            $parent.attr("id","tabpage"+index).siblings().hide();
            $nav.siblings().removeClass("current");
            me.current={
                pageData:pagedata,
                index:index
            };
            $iframe.load(function(){
                //$iframe.unloadover();
                if(icon){ $nav.find(".YFICON_loading").attr("src",icon);return;}
                if(url.indexOf(Ladder.BasicURL)>-1){
                    pagedata.icon=Ladder.BasicURL+"/images/menuIcon.png";
                    $nav.find(".YFICON_loading").attr("src",Ladder.BasicURL+"/images/menuIcon.png");
                    return;
                }
                var domain = url.match(/http[s]?:\/\/(.*?)([:\/]|$)/);//匹配指定URL的domain
                if(domain){
                    $nav.find(".YFICON_loading").attr("src",domain[0]+"/favicon.ico");
                }else{
                    $nav.find(".YFICON_loading").remove();
                }
            });
            $iframe.attr("src",url);
        },
        close:function(){

        }
    }
    Ladder.NS("NavMenu");
    Ladder.NavMenu=function(el,option){
        this.father=$(el);
        if(this.father.length<1)return;
        this.menuEl=null;
        this.settings={
            second:{
                left:'auto',
                top:60,
                width:200,
                height:700
            },
            data:null,
            onClick:null
        };
        $.extend(this.settings,option);
        this.init();
    }
    Ladder.NavMenu.prototype={
        init:function(){
            var me=this;
            if(!me.settings.data)return false;
            var $firstmenu=me.father.find(".yui-navmenu");
            if($firstmenu.length<1){
                $firstmenu=$('<ul class="yui-navmenu"></ul>');
                me.father.append($firstmenu);
            }
            this.menuEl=$firstmenu;
            var dataType=Ladder.getType(me.settings.data);
            if(dataType=='Array'){
                for(var i=0;i<me.settings.data.length;++i)this.add(me.settings.data[i]);
            }else{
                this.add(me.settings.data);
            }
        },
        add:function(node){
            var me=this;
            var $li=$('<li class="firstmenu"></li>');
            var $firstitem=$('<div class="firstitem"></div>');
            if(node.hasOwnProperty("icon")){
                if(! /\w*\.(gif)|(png)|(jpg)$/.test(node.icon)) {
                    if(node.icon.length > 100)node.icon = "data:image/png;base64," + node.icon;
                    else node.icon = "../../images/icon_default.png";
                }
            }else  node.icon="../../images/icon_default.png";
            $firstitem.append('<img src="'+node.icon+'" class="menuicon">');
            $firstitem.append('<span class="menutitle">'+node.title+'</span>');
            $li.append($firstitem);
            var $secondmenu=$('<div class="secondmenu"></div>');
            $secondmenu.append("<h2>"+node.title+"</h2>");
            var $seconditems=$("<ul></ul>");
            $secondmenu.append($seconditems);
            var dataType=Ladder.getType(node.children);
            //判断数据是数组还是单对象
            if(dataType=='Array'){
                for(var i=0;i<node.children.length;++i){
                    if(node.children[i].ispmenu){
                        _this.addsecondeItem($secondmenu,node.children[i]);
                    }else{
                        var $liy=$('<li class="seconditem">'+node.children[i].title+'</li>');
                        $seconditems.append($liy);
                        $liy.data("cmenudata",node.children[i]);
                        $liy.click(function(){
                            var data= $(this).data("cmenudata");
                            if(me.settings.onClick)me.settings.onClick(data);
                        })
                    }
                }
            }else if(dataType=='Object'){
                if(node.children){
                    $seconditems.append('<li class="seconditem">'+node.children.title+'</li>');
                }
            }
            //把数据填充到组件中
            $li.append($secondmenu);
            me.menuEl.append($li);
            //处理事件堆
            $li.hover(
                function(){
                    $(this).find(".secondmenu").css({
                        left:me.settings.second.left=='auto'?me.menuEl.width()+1:me.settings.second.left,
                        top:me.settings.second.top,
                        height:me.settings.second.height,
                        width:me.settings.second.width
                    });
                    $(this).find(".firstitem").addClass("hover");
                    $(this).find(".secondmenu").show();
                },
                function(){
                    $(this).find(".firstitem").removeClass("hover");
                    $(this).find(".secondmenu").hide();
                }
            )
        },
        addsecondeItem:function($secondmenu,node){
            if(!node.children || node.children.length<1)return;
            var me=this;
            $secondmenu.append("<h4>"+node.title+"</h4>");
            var $seconditems=$("<ul></ul>");
            //判断数据是数组还是单对象
            for(var i=0;i<node.children.length;++i){
                if(node.children[i].ispmenu){
                    me.addsecondeItem($secondmenu,node.children[i]);
                }else{
                    var $li=$('<li class="seconditem">'+node.children[i].title+'</li>');
                    $seconditems.append($li);
                    $li.data("cmenudata",node.children[i]);
                    $li.click(function(){
                        var data= $(this).data("cmenudata");
                        if(me.settings.onClick)me.settings.onClick(data);
                    });
                }
            }
            $secondmenu.append($seconditems);
        },
        swap:function(opt,callback){
            var _this=this;
            if(!_this.menuEl)return;
            if(opt==0 || _this.menuEl.width()==_this.option.uiwidth){
                _this.menuEl.find(".menutitle").hide(500);
                _this.menuEl.animate({width:40},500);
                if(callback)callback();
            }
            if(opt==1 || _this.menuEl.width() !=_this.option.uiwidth){
                _this.menuEl.animate({width:_this.option.uiwidth},500,function(){
                    _this.menuEl.find(".menutitle").show();
                });
                if(callback)callback();
            }
        },
        width:function(w){
            if(YFLib.getType(w)=="Number"){
                this.menuEl.width(w);return this.menuEl.width();
            }else{
                return this.menuEl.width();
            }
        },
        config:function(opt){
            if(opt){$.extend(this.option,opt);}
            else{return this.option};
        }
    };
    $.fn.tips= function (options) {
        var $this=$(this);
        var fid="tips"+Math.floor(Math.random()*1000);
        var dft = {
            showhtml:"友情提示，正在加载",
            timeout:0,
            width:"auto",
            height:16,
            "maskcolor":"rgba(10,10,10,0.5)",
            direction:"bottom",
            "borderwidth":10
        };
        var opt = $.extend(dft,options);
        if(opt.width=="aut0")opt.width=12*(opt.showhtml).length;
        if(opt.borderwidth*2+4>opt.height){
            opt.borderwidth=opt.height/2-4;
        }
        var e_tip=$("<div data-target='"+fid+"'></div>");
        e_tip.css({
            background:opt.maskcolor,
            position: "absolute",
            "z-index": 1000,
            padding:"4px",
            "border-radius":"4px",
            width:opt.width,
            height:opt.height,color:"#fff",//,opacity:0
            "font-size":"12px","font-weight":"bold"
        });
        e_tip.html(opt.showhtml);
        var e_tri=$("<div data-target='"+fid+"'></div>");
        e_tri.css({
            width: 0,height: 0,position: "absolute",
            "border-left": opt.borderwidth+"px solid transparent",
            "border-right": opt.borderwidth+"px solid transparent",
            "border-bottom": opt.borderwidth+"px solid transparent",
            "border-top": opt.borderwidth+"px solid transparent"
        });
        if(opt.direction=='top'){
            if($this.offset().top-opt.height-18<0){
                opt.direction='bottom';
            }else{
                e_tip.css({top:$this.offset().top-opt.height-15});
                e_tri.css({"border-bottom":0,"border-top": "10px solid "+opt.maskcolor,"bottom": "-10px"});
            }
        }
        if(opt.direction=='bottom'){
            if($this.offset().top+$this.height()+opt.height>=$(window).height()){
                opt.direction="right";
            }else{
                e_tip.css({top:$this.offset().top+$this.height()+12});
                e_tri.css({"border-top":0,"border-bottom": "10px solid "+opt.maskcolor,"top": "-10px"});
            }
        }
        if(opt.direction=='bottom'||opt.direction=='top'){
            var box_left=$this.offset().left+opt.width>$(window).width()?$(window).width()-opt.width:$this.offset().left;
            var c_left=$this.offset().left+($this.width()/2);
            var box_r=box_left+opt.width;
            var wz=0;
            if(c_left>box_r-10)wz=opt.width-25;
            if(c_left<box_left-10)wz=15;
            if(wz==0)wz=c_left-box_left-10;
            e_tip.css({left:box_left});
            e_tri.css({left:wz});
        }
        if(opt.direction=='right'){
            e_tip.css({
                top:$this.offset().top+($this.offset().height/2),
                left:$this.offset().left+$this.offset().width+15
            });
            console.log($this.offset().left);
            e_tri.css({
                "border-left":0,
                "border-right": "10px solid "+opt.maskcolor,
                left:"-10px",
                "top":(opt.height-opt.borderwidth)/2
            });
        }
        if(opt.direction=='left'){
            e_tip.css({
                top:$this.offset().top+(opt.height/2),
                left:$this.offset().left-opt.width-20
            });
            e_tri.css({
                "border-right":0,
                "border-left": "10px solid "+opt.maskcolor,
                left:opt.width+8,
                "top": "50%"
            });
        }
        e_tip.append(e_tri);
        $(document.body).append(e_tip);
        $this.attr("data-on",fid);
        if(opt.timeout>0){
            setTimeout(function(){
                $("[data-target="+fid+"]").remove();
            },opt.timeout);
        }
        return fid;
    }
    $.fn.untips=function(){
        var $this=$(this);
        var fid=$this.attr("data-on");
        $("[data-target="+fid+"]").remove();
    }

});